﻿using System.Collections.ObjectModel;
using System.Data.Common;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Messaging;
using DynamicData;
using Serilog;
using SimpleTool.ActivityUnit;
using SimpleTool.Base;
using SimpleTool.Server;
using SimpleTool.TransformComponent;
using static SimpleTool.SerialTool.SerialControl.CommandSectionModel;

namespace SimpleTool.SerialTool
{
    public class OverViewModel : Notify
    {
        public IPowerPlantServer PowerPlantServer;

        private readonly ILogger Logger = Log.ForContext<OverViewModel>();

        private ICommand? CmdLeisureContentStdin;

        private ICommand? CmdLeisureCommandStdin;

        private ICommand? CmdLeisureSubmitStdin;

        private ICommand? CmdLeisureFocusStdin;

        private ICommand? CmdLeisureWalkStdin;

        private ICommand? CmdClearSerialOutStdin;

        private Visibility VarbinNMLeisureCommandVisibleStdin = Visibility.Collapsed;

        private Visibility VarbinEDLeisureCommandVisibleStdin = Visibility.Collapsed;

        private UIBind VarbinUIBindStdin = new(Interfacial.SRLPConfig);

        public OverViewModel(IPowerPlantServer PowerServer)
        {
            PowerPlantServer = PowerServer;

            TopMenuOptionsLoad();

            CmdEditItemsSource(); //  加载指令编辑选项源

            WeakReferenceMessenger.Default.Register<MvvmMessage>(this, MvvmMessageProcessPlant);
        }

        public void CmdEditItemsSource()
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                foreach (var kvp in ActivityAssistBehivor.Behivor.AttributeExpectsMap)
                {
                    if (kvp.Key.Contains("Command"))
                    {
                        Edit_ComadItemsSources.AddRange(kvp.Value);
                    }
                    else if (kvp.Key.Contains("Step"))
                    {
                        Edit_AliasItemsSources.AddRange(kvp.Value);
                    }
                }
            }, System.Windows.Threading.DispatcherPriority.Background);
        }

        public OverSectionModel HoldOverSectionModel { set; get; } = new OverSectionModel();

        public ICommand CmdLeisureContent
        {
            set
            {
                CmdLeisureContentStdin = value;
                propertyChangeSend(nameof(CmdLeisureContent));
            }
            get
            {
                CmdLeisureContentStdin ??= new EasyCommand(FreeCommandWrite, bool () => { return true; });
                return CmdLeisureContentStdin;
            }
        }

        //  通知组件开始获取指令文本
        public ICommand CmdLeisureCommand
        {
            set
            {
                CmdLeisureCommandStdin = value;
            }
            get
            {
                CmdLeisureCommandStdin ??= new EasyCommand(FreeCommandNotifyExecute, bool () => { return true; });
                return CmdLeisureCommandStdin;
            }
        }

        public ICommand CmdLeisureSubmit
        {
            set
            {
                CmdLeisureSubmitStdin = value;
            }
            get
            {
                CmdLeisureSubmitStdin ??= new EasyCommand(EchoCommandEditUpdate, bool () => { return true; });
                return CmdLeisureSubmitStdin;
            }
        }

        public ICommand CmdLeisureFocus
        {
            set
            {
                CmdLeisureFocusStdin = value;
            }
            get
            {
                CmdLeisureFocusStdin ??= new EasyCommand(CmdEchoFocusEvent, bool () => { return true; });
                return CmdLeisureFocusStdin;
            }
        }

        public ICommand CmdLeisureWalk
        {
            set
            {
                CmdLeisureWalkStdin = value;
            }
            get
            {
                CmdLeisureWalkStdin ??= new EasyCommand(CmdEchoWalkEvent, bool () => { return true; });
                return CmdLeisureWalkStdin;
            }
        }

        public ICommand CmdClearSerialOut
        {
            set
            {
                CmdClearSerialOutStdin = value;
            }
            get
            {
                CmdClearSerialOutStdin ??= new EasyCommand(ClearSerialOutEvent, bool () => true);
                return CmdClearSerialOutStdin;
            }
        }

        public Visibility VarbinNMLeisureCommandVisible
        {
            set
            {
                VarbinNMLeisureCommandVisibleStdin = value;
                propertyChangeSend(nameof(VarbinNMLeisureCommandVisible));
            }
            get
            {
                return VarbinNMLeisureCommandVisibleStdin;
            }
        }

        public Visibility VarbinEDLeisureCommandVisible
        {
            set
            {
                VarbinEDLeisureCommandVisibleStdin = value;
                propertyChangeSend(nameof(VarbinEDLeisureCommandVisible));
            }
            get
            {
                return VarbinEDLeisureCommandVisibleStdin;
            }
        }

        public double VarbinCommandEchoOpacityStdin = 0;

        public object? VarbinControlContentStdin;

        private Deserted? MainDesertedOptionsStdin;

        private Deserted? ChildDesertedOptionsStdin;

        //  指令编辑组件渐变值
        public double VarbinCommandEchoOpacity
        {
            set
            {
                VarbinCommandEchoOpacityStdin = value;
                propertyChangeSend(nameof(VarbinCommandEchoOpacity));
            }
            get
            {
                return VarbinCommandEchoOpacityStdin;
            }
        }

        public UIBind VarbinUIBind
        {
            set
            {
                VarbinUIBindStdin = value;
                propertyChangeSend(nameof(VarbinUIBind));
            }
            get
            {
                return VarbinUIBindStdin;
            }
        }

        public AlterCommandStruct EchoCommandInfo 
        { 
            set 
            {
                HoldOverSectionModel.EchoCommandInfoStdin = value;
                propertyChangeSend(nameof(EchoCommandInfo));
            } 
            get 
            {
                return HoldOverSectionModel.EchoCommandInfoStdin;
            } 
        }

        public Deserted HoldMainDesertedOptions
        {
            get
            {
                MainDesertedOptionsStdin ??= new Deserted();
                return MainDesertedOptionsStdin;
            }
        } 

        public Deserted HoldChildDesertedOptions
        {
            get
            {
                ChildDesertedOptionsStdin ??= new Deserted();
                return ChildDesertedOptionsStdin;
            }
        }

        //  文本框数据
        public ObservableCollection<object> DynamicRichContent { set; get; } = [];

        public ObservableCollection<string> Edit_ComadItemsSources { set; get; } = [];

        public ObservableCollection<string> Edit_AliasItemsSources { set; get; } = [];

        public ObservableCollection<TopMenuOptions> HoldTopMenuOptions { set; get; } = [];

        private static void MvvmMessageProcessPlant(object recipient, MvvmMessage message)
        {
            OverViewModel self = (OverViewModel)recipient;
            switch (message.Type)
            {
                case MvvmMessage.MvvmType.Command_EditInfoGet:
                    self.UnexpectedCmdInfoEcho(message);
                    break;

                case MvvmMessage.MvvmType.SerialPort_ChildPage:
                    self.PageTypeChange(message);
                    break;
            }
        }

        private void PageTypeChange(MvvmMessage message)
        {
            if (message.MsgBody is not null and int _type)
            {
                Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        switch (_type)
                        {
                            case 2:
                                VarbinUIBind.UIType = Interfacial.SRLPConfig;
                                VarbinNMLeisureCommandVisible = Visibility.Visible;
                                break;

                            case 3:
                                VarbinUIBind.UIType = Interfacial.SRLPCommand;
                                VarbinNMLeisureCommandVisible = Visibility.Visible;
                                break;
                        }
                        propertyChangeSend(nameof(VarbinUIBind));
                    }
                    catch (Exception error)
                    {
                        Logger.Print(RuntimeLog.LogType.Debug, $"{MethodBase.GetCurrentMethod()?.Name} {error.Message}");
                    }
                });
            }
        }

        //  更新已编辑的指令信息
        private void EchoCommandEditUpdate(object? param)
        {
            WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Command_EditInfoSend, EchoCommandInfo));
        }

        //  指令编辑组件聚焦
        private async void CmdEchoFocusEvent(object? param)
        {
            if (param is not null && bool.TryParse(param.GetSafetyChar(), out bool isGotFocus))
            {
                HoldOverSectionModel.CommandEchoisGotFocus = isGotFocus;
                await CmdEchoOpacityGradent();
            }
        }

        //  指令编辑组件失焦
        private async void CmdEchoWalkEvent(object? param)
        {
            if (param is not null && bool.TryParse(param.GetSafetyChar(), out bool isWalking))
            {
                HoldOverSectionModel.CommandEchoisWalking = isWalking;
                await CmdEchoOpacityGradent();
            }
        }

        //  指令组件渐变执行
        private async Task CmdEchoOpacityGradent()
        {
            if (HoldOverSectionModel.CommandEchoisWalking)
            {
                VarbinEDLeisureCommandVisible = Visibility.Visible;
                while (HoldOverSectionModel.CommandEchoisWalking)
                {
                    if (Math.Round(VarbinCommandEchoOpacity, 1) >= 1.0 || !HoldOverSectionModel.CommandEchoisWalking)
                    {
                        break;
                    }
                    else
                    {
                        VarbinCommandEchoOpacity += 0.1;
                    }
                    await Task.Delay(50);
                }
            }
            else
            {
                await Task.Delay(3000);
                while (!HoldOverSectionModel.CommandEchoisGotFocus && !HoldOverSectionModel.CommandEchoisWalking)
                {
                    if (Math.Round(VarbinCommandEchoOpacity, 1) <= 0.0 || HoldOverSectionModel.CommandEchoisWalking)
                    {
                        VarbinEDLeisureCommandVisible = Visibility.Collapsed;
                        break;
                    }
                    else
                    {
                        VarbinCommandEchoOpacity -= 0.1;
                    }
                    await Task.Delay(50);
                }
            }
        }

        //  串口数据接收
        public void SerialDataReceive(string receive)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                string timeTemp = DateTime.Now.ToString("HH:mm:ss");
                DynamicRichContent.Add(new EnjoyRichTextBox.Text
                {
                    Contnet = $"[{timeTemp}] {receive}"
                });
            });
        }

        //  获取右下指令信息，发送标识至组件中，组件发送文本框内容
        private void FreeCommandNotifyExecute(object? param)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
           
                HoldChildDesertedOptions.CapCTRichBox = true;
            });
        }

        //  执行右下角文本框指令，可通过@分割多条指令执行
        private void FreeCommandWrite(object? param)
        {
            if (param is not null and string command)
            {
                PowerPlantServer.Execute(command);
            }
        }

        //  显示选中的指令信息
        private async void UnexpectedCmdInfoEcho(MvvmMessage message)
        {
            if (message.MsgBody is AlterCommandStruct alterInfo)
            {
                var alterCommand = new AlterCommandStruct(alterInfo.AlterCommand, alterInfo.AlterIndex);
                EchoCommandInfo = alterCommand;
                HoldOverSectionModel.CommandEchoisWalking = true;
                await CmdEchoOpacityGradent();
            }
        }

        //  清除串口输出
        private void ClearSerialOutEvent(object? param)
        {
            HoldMainDesertedOptions.DoCtClearRichBox = true;
        }

        //  顶部菜单加载
        private void TopMenuOptionsLoad()
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                HoldTopMenuOptions.Clear();

                HoldTopMenuOptions.Add
                (
                    new TopMenuOptions
                    {
                        Icon = "\ue626",
                        MenuName = "清空串口输出",
                        Command = CmdClearSerialOut
                    }
                );
            });
        }
    }
}
